import Taro, { useState, usePullDownRefresh, useDidShow, useEffect }  from '@tarojs/taro'
import { View, Image } from '@tarojs/components'
import { AtTabs, AtTabsPane, AtAccordion, AtIcon } from 'taro-ui'
import m from 'moment'
import _get from 'lodash/get'

// component
import NoData from "../../components/noData";


// const
import { OSS_IMAGE_URL_PREFIX } from '../../constances/constances'

// utils
import getLoginInfo from "../../utils/getLoginInfo"

// api
import api from '../../api/index'

// style
import './index.scss'

export default function RecordingList() {
  const [current, setCurrent] = useState(0)
  const [timeMap, setTimeMap] = useState({})
  const [albumMap, setAlbumMap] = useState({})
  const [opens, setOpens] = useState([])
  const [userData, setuserData] = useState({})
  const [loading, setLoading] = useState(false)

  const tabList = [{ title: '按专辑' }, { title: '按时间' }]


  useDidShow(() => {
    // 加载用户数据
    console.log('刷新一下')
    const user = getLoginInfo()
    setuserData(user)
    if (user) {
      initPage(user)
    } else {
      Taro.showToast({
        title: '请先登录',
        icon: 'none'
      })
    }
  })

  usePullDownRefresh(() => {
    initPage(userData).then(() => {
      Taro.stopPullDownRefresh()
    }).catch(() => {
      Taro.stopPullDownRefresh()
    })
  })

  // 初始化页面
  async function initPage(_user) {
    setLoading(true)
    try {
      const data = await api.recording.getList({
        uid: _get(_user, ['user', 'user_id']),
        orgid: _get(_user, ['user', 'organization', 'org_id'])
      })


      setLoading(false)

      const _albumMap = {};
      const _timeMap = {};

      if (data && data.recordingList) {
        data.recordingList.reverse().map(record => {
          const time = m(record.date_time).format('YYYY-MM-DD')
          if ((record.cover_image_key == null) || (record.cover_image_key === "")) { record.cover = require("../../assets/DefaultCover.png"); }
          else { record.cover = OSS_IMAGE_URL_PREFIX + "/" + record.episode + "/" + record.book + "/" + record.cover_image_key; }

          // ctype
          // record.link = "/?uid=" + record.user_id + "&recid=" + record.id + (this.ctype ? `&ctype=${this.ctype}` : '')
          record.link = "/?uid=" + record.user_id + "&recid=" + record.id

          if (_albumMap[record.episode]) {
            _albumMap[record.episode].push(record)
          } else {
            _albumMap[record.episode] = [record]
          }

          if (_timeMap[time]) {
            _timeMap[time].push(record)
          } else {
            _timeMap[time] = [record]
          }

          return {
            ...record,
            time
          }
        })

        setAlbumMap(_albumMap)
        setTimeMap(_timeMap)

      }
    } catch (e) {
      setLoading(false)
      Taro.showToast({
        title: '网络错误',
        icon: 'none'
      })
    }
  }

  function handleOpen(key) {
    const index = opens.findIndex(item => key === item)
    if (index > -1) {
      const _m = [...opens]
      _m.splice(index, 1);
      setOpens(_m)
    } else {
      setOpens([
        ...opens,
        key
      ])
    }
  }

  function goRecording(id) {
    Taro.navigateTo({
      url: `/pages/recording/index?recid=${id}&uid=${userData.user.user_id}`
    })
  }

  return (
    <View className='home-page'>
      <AtTabs current={current} tabList={tabList} onClick={value => setCurrent(value)}>
        <AtTabsPane current={current} index={0} >
          <View className='tabsPane'>
            {
              Object.keys(albumMap).map((key, index) => {
                return (
                  <AtAccordion isAnimation={false} open={opens.findIndex(open => open === key) > -1} title={key} key={index} onClick={() => handleOpen(key)}>
                    {
                      albumMap[key].map(recording => {
                        return (
                          <View className='recording' key={recording.id} onClick={() => goRecording(recording.id)}>
                            <Image src={recording.cover} className='cover' mode='aspectFit' />
                            <View className='content'>
                              <View className='title'>{ recording.book } </View>
                            </View>
                            <AtIcon className='icon' value='chevron-right' size='20' color='#cecece' />
                          </View>
                        )
                      })
                    }
                  </AtAccordion>
                )
              })
            }
          </View>
        </AtTabsPane>
        <AtTabsPane current={current} index={1}>
          <View className='tabsPane'>

            {
              Object.keys(timeMap).map((key, index) => {
                return (
                  <AtAccordion isAnimation={false} open={opens.findIndex(open => open === key) > -1} title={key} key={index} onClick={() => handleOpen(key)}>
                    {
                      timeMap[key].map(recording => {
                        return (
                          <View className='recording' key={recording.id} onClick={() => goRecording(recording.id)}>
                            <Image src={recording.cover} className='cover' mode='aspectFit' />
                            <View className='content'>
                              <View className='title'> { recording.book } </View>
                            </View>
                            <AtIcon className='icon' value='chevron-right' size='20' color='#cecece' />
                          </View>
                        )
                      })
                    }
                  </AtAccordion>
                )
              })
            }

          </View>
        </AtTabsPane>
      </AtTabs>
      {
        loading ? (
          <View className='list-tips'>
            加载中...
          </View>
        ) : (
          (Object.keys(albumMap).length === 0 || Object.keys(timeMap).length === 0) && (
            <View className='list-tips'>
              <NoData />
            </View>
          )
        )
      }
    </View>
  )
}

RecordingList.config = {
  navigationBarTitleText: '首页',
  enablePullDownRefresh: true
}
